using System;
using Tycho.Parser.Peg;

namespace Tycho.Grammar {
    class NonTerminalRuleCompiler : INonTerminalRuleCompiler {
        private readonly IRuleCompiler RuleCompiler;
        private readonly Func<ICaptureCounter> CreateCaptureCounter;
        public NonTerminalRuleCompiler (IRuleCompiler ruleCompiler) : this (ruleCompiler, () => new CaptureCounter ()) {}

        public NonTerminalRuleCompiler (IRuleCompiler ruleCompiler, Func<ICaptureCounter> createCaptureCounter) {
            RuleCompiler = ruleCompiler;
            CreateCaptureCounter = createCaptureCounter;
        }

        public RuleCaptures Compile (ITerm rule, ProductionCompilerContext context) {
            ICaptureCounter captureCounter = CreateCaptureCounter ();
            IRule compiledRule = RuleCompiler.Compile (rule, context, captureCounter);

            return new RuleCaptures {
                                        Rule = compiledRule,
                                        MultipleCaptures = captureCounter.MultipleCaptures,
                                        FirstCapture = captureCounter.FirstCapture,
                                        LastCapture = captureCounter.LastCapture,
                                    };
        }
    }
}